<template>
  <div class="app-container">

    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top" label-width="100%">

      <el-card>

        <el-form-item label="证书名称" prop="title">
          <el-input v-model="postForm.title" />
        </el-form-item>

        <el-form-item label="证书备注" prop="remark">
          <el-input v-model="postForm.remark" type="textarea" />
        </el-form-item>

        <el-form-item label="证书编号" prop="code">
          <el-input v-model="postForm.code" type="textarea" />
        </el-form-item>

        <el-form-item label="证书模板">
          <file-upload v-model="postForm.backLogo" accept=".pptx" :tip="'请上传PowerPoint格式(.pptx)的证书模板文件'"/>
        </el-form-item>

      </el-card>

      <div style="margin-top: 20px">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="info" @click="onCancel">返回</el-button>
      </div>

    </el-form>

  </div>
</template>

<script>

import { fetchDetail, saveData, getExamsByCertId, bindCertToExam, unbindCertFromExam } from '@/api/cert/cert'
import { fetchList } from '@/api/exam/exam'
import { get } from '@/utils/request'
import FileUpload from "@/components/FileUpload/index.vue";

export default {
  name: 'CrdeDetail',
  components: {FileUpload},
  data() {
    return {
      postForm: {

      },
      examList: [], // 考试列表
      selectedExams: [], // 选中的考试ID列表
      originalExams: [], // 原始关联的考试ID列表
      loading: false,
      rules: {

        title: [
          { required: true, message: '证书名称不能为空！' }
        ]
      }
    }
  },
  created() {
    // 获取考试列表
    this.fetchExamList()

    const id = this.$route.params.id
    if (typeof id !== 'undefined') {
      this.fetchData(id)
    }
  },
  methods: {

    // 添加子项
    handleAdd() {
      this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
    },

    fetchData(id) {
      const params = { id: id }
      fetchDetail(params).then(response => {
        this.postForm = response.data
        // 获取证书关联的考试
        this.fetchCertExams(id)
      })
    },

    // 获取考试列表
    fetchExamList() {
      fetchList().then(response => {
        this.examList = response.data.records || response.data || []
      }).catch(error => {
        console.error('获取考试列表失败:', error)
        this.$message.error('获取考试列表失败')
      })
    },

    // 获取证书关联的考试
    fetchCertExams(certId) {
      get(`/exam/api/cert/exams/${certId}`).then(response => {
        const examIds = response.data.map(item => item.examId)
        this.selectedExams = examIds
        this.originalExams = [...examIds] // 保存原始状态
      }).catch(error => {
        console.error('获取证书关联考试失败:', error)
      })
    },
    //修改证书
    submitForm() {
      console.log(JSON.stringify(this.postForm))

      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.loading = true
        this.postForm.creationTime = null;

        saveData(this.postForm).then((response) => {
          const certId = this.postForm.id || response.data.id

          // 保存考试绑定关系
          return this.saveExamBindings(certId)
        }).then(() => {
          this.loading = false
          this.$notify({
            title: '成功',
            message: '证书保存成功！',
            type: 'success',
            duration: 2000
          })

          this.$router.push({ name: 'ListCert' })
        }).catch(error => {
          this.loading = false
          console.error('保存失败:', error)
          this.$message.error('保存失败')
        })
      })
    },

    // 保存考试绑定关系
    async saveExamBindings(certId) {
      if (!certId) return

      // 计算需要新增和删除的考试
      const toAdd = this.selectedExams.filter(examId => !this.originalExams.includes(examId))
      const toRemove = this.originalExams.filter(examId => !this.selectedExams.includes(examId))

      // 执行绑定操作
      const promises = []

      // 新增绑定
       toAdd.forEach(examId => {
         promises.push(
           bindCertToExam(examId, certId)
         )
       })

       // 删除绑定
       toRemove.forEach(examId => {
         promises.push(
           unbindCertFromExam(examId, certId)
         )
       })

      if (promises.length > 0) {
        await Promise.all(promises)
      }
    },

    onCancel() {
      this.$router.push({ name: 'ListRepo' })
    },
    hand1(){
      alert(this.postForm.backLogo)
    }

  }
}
</script>

<style scoped>
.exam-selection {
  width: 100%;
}

.exam-selection .el-select {
  width: 100%;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-card {
  margin-bottom: 20px;
}
</style>
